package game;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.Border;

import datastructures.Coordinate;

/**
 * @author Fredrik
 *
 */
public class MapPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 330233704432420241L;
	
	private static final int WIDTH = 200;
	private static final int HEIGHT = 150;

	private MainModel model;

	/**
	 * Constructor creating a new map panel
	 * @param model
	 * @param controller
	 */
	public MapPanel(MainModel model, MainController controller) {
		this.model = model;

		this.setBounds(0, 0, WIDTH, HEIGHT);
		this.addMouseListener(controller);
		Border border = BorderFactory.createEmptyBorder(0, 0, HEIGHT, WIDTH);
		this.setBorder(border);
	}

	/** (non-Javadoc)
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	@Override
	public void paintComponent(Graphics g) {
		int width = this.model.getWidth();
		int height = this.model.getHeight();

		Coordinate c;
		g.setColor(Color.YELLOW);
		for(int x = 0; x< width;x++){
			for(int y = 0; y < height; y++){
				c = new Coordinate(x,y);
				if(this.model.isWindowUnlocked(c)){
					drawRec(g,c,width,height);
				}
			}
		}
		
		c = this.model.getCurrentWindowCordinates();
		
		g.setColor(Color.RED);
		
		drawRec(g,c,width,height);
		
		
		g.setColor(Color.BLACK);
		
		for (int x = 0; x < width + 1; x++) {
			g.drawLine(x * (WIDTH / width), 0, x * (WIDTH / width), HEIGHT);
		}

		for (int y = 0; y < height + 1; y++) {
			g.drawLine(0, y * (HEIGHT / height), WIDTH, y * (HEIGHT / height));
		}
		
		

	}
	
	private void drawRec(Graphics g, Coordinate c,int width,int height){
		g.fillRect(c.getX()*(WIDTH / width), c.getY()*(HEIGHT / height), (WIDTH / width), (HEIGHT / height));
	}
	
	/**
	 * Returns new selected coordinates by calculating where on the map a user pressed
	 * @param c
	 * @return new selected coordinates
	 */
	public Coordinate getNewCoordinate(Coordinate c){
		int width = this.model.getWidth();
		int height = this.model.getHeight();
		int x = (c.getX()*width)/WIDTH;
		int y = (c.getY()*height)/HEIGHT;
		if(x>=width)
			x = width-1;
		if(y>=height)
			y=height-1;
		Coordinate retVal = new Coordinate(x,y);
		return retVal;
	}

}
